import StackManager from './StackManager';
import filterDWIImageIds from './filterDWIImageIds';
import cornerstone from 'cornerstone-core';

export default (studies, displaySet, filterDWI = false) => {
  const { StudyInstanceUID, displaySetInstanceUID, SOPInstanceUID, frameIndex } = displaySet;

  const study = studies.find(
    study => study.StudyInstanceUID === StudyInstanceUID
  );

  const displaySetDetails = study.displaySets.find(set => {
    return set.displaySetInstanceUID === displaySetInstanceUID;
  });

  // Get stack from Stack Manager
  const storedStack = StackManager.findOrCreateStack(study, displaySetDetails);

  // Clone the stack here so we don't mutate it
  const stack = Object.assign({}, storedStack);
  if (filterDWI) {
    stack.imageIds = filterDWIImageIds(stack.imageIds);
  }

  if (frameIndex && frameIndex < stack.imageIds.length) {
    stack.currentImageIdIndex = frameIndex;
  } else if (SOPInstanceUID) {
    const index = stack.imageIds.findIndex(imageId => {
      const imageIdSOPInstanceUID = cornerstone.metaData.get(
        'SOPInstanceUID',
        imageId
      );

      return imageIdSOPInstanceUID === SOPInstanceUID;
    });

    if (index > -1) {
      stack.currentImageIdIndex = index;
    } else {
      stack.currentImageIdIndex = 0;
    }
  } else {
    stack.currentImageIdIndex = 0;
  }

  return stack;
}
